<template>
  <form action="/">
    <van-search shape="round"
                autofocus="true"
                v-model="searchTest"
                show-action
                placeholder="请输入搜索关键词"
                @search="onSearch"
                @cancel="onCancel"

    />
    <van-divider content-position="left"
                 :style="{ color: '#1989fa', borderColor: '#4219fa', padding: '0 16px' }">
      已选标签
    </van-divider>
    <van-row gutter="16">
      <van-col v-for='tag in activeId' style="padding: 10px 15px">
        <van-tag show=true closeable size="medium" type="primary" @close="doClose(tag)">
          {{ tag }}
        </van-tag>
      </van-col>
    </van-row>

  </form>
  <van-divider content-position="left"
               :style="{ color: '#1973fa', borderColor: '#19fabe', padding: '0 16px' }">
    可选标签
  </van-divider>
  <van-tree-select
      v-model:active-id="activeId"
      v-model:main-active-index="activeIndex"
      :items="tagNames"
  />
  <div>
    <van-button style="width: 200px;background-color: #00b2ff" round @click="doSearchResult">
      <p style="color: rgb(40,33,71);font-size: 16px">搜索</p>
    </van-button>
  </div>

</template>
<script setup>
import {ref} from 'vue';
import {useRouter} from "vue-router";

const router = useRouter()
//选中的参数
const activeId = ref([]);
const activeIndex = ref(0);
//搜索框参数
const searchTest = ref('');

//搜索时过滤
const onSearch = (val) => {
  tagNames.value = originTagNames.map(parentTag => {
    //map用来扁平化数组，克隆一个tag的children
    const tempChildren = [...parentTag.children];
    console.log(tempChildren)
    //克隆tag,包含children
    const tempParentTag = {...parentTag};
    console.log(tempParentTag)
    //过滤出来children中包含searchTest的内容组成一个新的数组，保留为返回值为true的内容
    tempParentTag.children = tempChildren.filter(item => item.text.includes(searchTest.value));
    return tempParentTag;
  })

}
//取消时
const onCancel = () => {
  searchTest.value = ''
  tagNames.value = originTagNames;
};

const doSearchResult = () => {
  router.push({
    path: '/user/searchResultPage',
    query: {tags: activeId.value}
  })
}

//取消标签
const doClose = (tag) => {
  //保留返回false的，如果不等于要删除的内容则保留
  activeId.value = activeId.value.filter(item => {
    return item != tag
  })
}

const originTagNames = [
  {
    text: '性别',
    children: [
      {text: '男', id: '男'},
      {text: '女', id: '女'},
    ],
  },
  {
    text: '方向',
    children: [
      {text: 'java', id: 'java'},
      {text: 'C++', id: 'C++'},
      {text: 'Golang', id: 'Golang'},
    ],
  },
  {
    text: '目标',
    children: [
      {text: '考公', id: '考公'},
      {text: '考研', id: '考研'},
      {text: '游戏组队', id: '游戏组队'},
    ],
  },
  {
    text: '段位',
    children: [
      {text: '青铜', id: '青铜'},
      {text: '白银', id: '白银'},
      {text: '王者', id: '王者'},
    ],
  }
]
const tagNames = ref(originTagNames);
</script>
<style scoped>

</style>